var config = $.extend(true, {}, listApp, {
    data: {
        service: protocolcService,
        protocolId: '',
        stype: '',
        editIndex: -1,
        addAble: true,
        isEdit: false,
        mids: [],
        selectedRows: [],
        selectedIds: [],
        repeated: false,
        currentChannelId: '',
        tableVm: {
            pageSize: 1000
        },
        searchVm: {
            mid: '',
            name: '',
            protocolId: '',
            trap: 1
        },
        translateEditVm: {
            formName: "exchangeEditForm",
            form: {
                data: [],
            },
            visible: false,
            oprate: "数值转译",
            channelId: '',
            rules: {
                key: [{required: true, message: '请输入采集数值', trigger: 'blur'}, {
                    validator: function (rule, value, callback) {
                        var regPos = /^[,|]$/
                        if (!regPos.test(value)) {
                            callback();
                        } else {
                            callback(new Error('不能输入“，”,“|”'));
                        }
                    },
                    trigger: 'blur'
                }],
                value: [{required: true, message: '请输入转译数值', trigger: 'blur'}, {
                    validator: function (rule, value, callback) {
                        var regPos = /^[,|]$/
                        if (!regPos.test(value)) {
                            callback();
                        } else {
                            callback(new Error('不能输入“，”,“|”'));
                        }
                    },
                    trigger: 'blur'
                }]
            },
            channelCode: '',
            channelName: '',
            requestPagePath : 'requestPageExt'
        },
    },
    methods: {
        init: function () {
            let fullUrl = window.location.href;
            this.id = this.getUrlKey("id", fullUrl);
            this.protocolName = this.getUrlKey("protocolName", fullUrl);
            // console.log("protocolName",this.protocolName)
            this.searchVm.protocolId = this.id;
        },
        translate: function (index, row) {
            console.log(row);
            var _this = this;
            _this.translateEditVm.channelCode = row.channelCode;
            _this.translateEditVm.channelName = row.name;
            _this.translateEditVm.form.data = [];
            this.translateEditVm.channelId = row.id;
            var items = row.translate.split(',');
            if (row.translate.length > 0 && items.length > 0) {
                items.forEach(function (val) {
                    // console.log(val+"\n")
                    var vals = val.split('|');
                    _this.translateEditVm.form.data.push({
                        isEdit: false,
                        key: vals[0],
                        value: vals[1]
                    });
                })
            }

            this.translateEditVm.visible = true;
        },
        addTranslate: function () {
            this.translateEditVm.form.data.push({
                isEdit: true,
                key: '',
                value: ''
            });
        },
        saveTranslate: function (index, row) {
            if (row == undefined || row.key == undefined || row.value == undefined || row.key == "" || row.value == "") {
                this.showFailMsg("采集数值或转译数值未填写！");
                return false;
            }
            if(row!=undefined && row.key!=undefined && (row.key.indexOf(",")!=-1 || row.key.indexOf("|") !=-1)){
                this.showFailMsg("采集数值不能包含“,”,“|”！");
                return false;
            }
            if(row!=undefined && row.value!=undefined && (row.value.indexOf(",")!=-1 || row.value.indexOf("|") !=-1)){
                this.showFailMsg("译数值不能包含“,”,“|”！");
                return false;
            }

            row.isEdit=false;
            this.saveTranslateVal(index,row);
        },
        editTranslate: function (index, row) {
            row.isEdit = true;
        },
        deleteTranslate: function (index, row) {
            this.translateEditVm.form.data.splice(index, 1);
            this.saveTranslateVal(index, row);
        },
        saveTranslateVal: function (index, row) {
            var _this = this;
            if (row == undefined || row.key == undefined || row.value == undefined || row.key == "" || row.value == "")
                return false;

            // console.log('channelId',this.translateEditVm.channelId,this.translateEditVm.data);

            var strTranslateVal = "";
            var valArr = [];
            this.translateEditVm.form.data.forEach(function (val) {
                valArr.push(val.key.concat('|').concat(val.value));
            })
            strTranslateVal = valArr.join(',');
            // console.log('strTranslateVal=',strTranslateVal);

            var param = {
                id: this.translateEditVm.channelId,
                translate: strTranslateVal
            }
            _HTTP.post("/api/protocolc/updateTranslate", param, {
                success: function (ret) {
                    if (ret.code === 200) {
                        _this.search();
                    } else {
                        _this.showFailMsg(ret.msg)
                    }
                },
                fail: function (res) {
                    _this.showFailMsg(res.msg);
                }
            })
        },
        renderTranslateHeader: function (h, {column, $index}) {
            // console.log('renderTranslateHeader',column)
            return h('span', {slot: 'reference',}, [
                h('span', {style: 'color:red;'}, '*'),
                h('span', {}, column.label),
            ])
        },
        maddRow: function () {
            this.getMaxChannelCode();
            this.isEdit = true;
            this.addAble = false;
            this.editIndex = 0;
            this.selectedIds = []
            this.selectedRows = []
            this.$refs.multipleTable.bodyWrapper.scrollTop = 0;
        },
        mdeleteRow: function (selectedRows) {
            var _this = this;
            var selectedIds = []
            selectedRows.forEach(row => {
                selectedIds.push(row.id)
            })
            this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(function () {
                _this.deleteLoading = true;
                let req = {
                    protocolId: _this.id,
                    protocolcIds: selectedIds
                }
                _HTTP.post("/api/protocolc/deleteRows", req, {
                    success(res) {
                        _this.deleteLoading = false;
                        _this.buildCurrentSearch();
                        _this.requsetPage();
                        _this.showSuccessMsg("操作成功！");
                    },
                    fail(res) {
                        _this.deleteLoading = false;
                        _this.showFailMsg(res.msg);
                    }
                })
            });
        },
        medit: function (index, row) {
            this.isEdit = true;
            this.addAble = false
            this.editIndex = index;
            this.edit(index, row)
            this.selectedIds = []
            this.selectedRows = []
        },
        msave: function (index, row) {
            const _this = this;
            row.protocolId = this.id;
            row.protocolName = this.protocolName;
            // row.channelCode = this.currentChannelId
            row.trap = 1
            row.dataType = 1
            this.editVm.data = row;
            _HTTP.post("/api/protocolc/saveAProtocolc", row, {
                success(res) {
                    if (res.content === '保存成功！') {
                        _this.showSuccessMsg(res.content)
                        _this.requsetPage()
                        _this.isEdit = false;
                        _this.editIndex = -1;
                        _this.addAble = true;
                    } else {
                        _this.showFailMsg(res.content)
                    }
                },
                fail(res) {
                    console.log(res)
                }
            })
        },
        cancel: function (row) {
            this.isEdit = false;
            this.editIndex = -1;
            this.addAble = true;
            this.requsetPage();
        },
        handleSelectionChange: function (rows) {
            if (rows == null || rows.length <= 0) {
                this.selectedIds = []
                this.selectedRows = []
                return
            }
            if (this.isEdit) {
                this.selectedIds = []
                this.selectedRows = []
                return
            }
            let that = this;
            this.selectedRows = rows
        },
        /**
         * 返回上一页
         */
        goBack: function () {
            let url = top._CTX + '/web/protocol/main'
            let iframe = parent.window.document.getElementById("menuFrame")
            iframe.setAttribute("src", url)
        },
        getMaxChannelCode: function () {
            let that = this;
            _HTTP.get("/api/protocolc/getMaxChannel?protocolId=" + this.id + "&trap=1", "", {
                success(res) {
                    // console.log(res)
                    that.channelCode = res.content
                    // console.log('channelCodes',res)
                    if (that.channelCode != null && that.channelCode !== '') {
                        let maxId = parseInt(that.channelCode.substring(1))
                        // console.log('maxId',that.channelCodes[0].substring(1))
                        for (let i = 1; i < 1000; i++) {
                            if (i > maxId) {
                                if (i < 10) {
                                    that.currentChannelId = "t00" + i
                                } else if (i >= 10 && i < 100) {
                                    that.currentChannelId = "t0" + i
                                } else if (i >= 1000) {
                                    that.currentChannelId = 't999'
                                } else {
                                    that.currentChannelId = 't' + i
                                }
                                break;
                            }
                        }
                        // console.log(that.currentChannelId)
                        that.tableVm.data.splice(0, 0, {
                            channelCode: that.currentChannelId
                        });
                    } else {
                        that.tableVm.data.splice(0, 0, {
                            channelCode: 't001'
                        });
                        that.currentChannelId = 't001'
                    }
                },
                fail(res) {
                    // console.log(res)
                }
            })
        },
        /**
         * 获取传参
         * @param name
         * @param url
         * @returns {string|null}
         */
        getUrlKey: function (name, url) {
            return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ""])[1].replace(/\+/g, '%20')) || null
        }
    }
});
var app = new Vue(config)